package com.jrx.anytxn.param.job.partition.config;


import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.param.config.AnytxnBatchProperties;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.mapper.ext.ExtTlFilePaymentLogMapper;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.Date;


/**
 * @author 张靖烽
 * @name RepayFileLogPartitionConfiguration
 * @description 还款文件表分区维护
 * @create 2021-03-10 16:06
 **/
@Configuration
@EnableConfigurationProperties(AnytxnBatchProperties.class)
public class RepayFileLogPartitionConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(RepayFileLogPartitionConfiguration.class);

    @Autowired
    public JobBuilderFactory jobBuilderFactory;
    @Autowired
    public StepBuilderFactory stepBuilderFactory;
    @Autowired
    private IOrganizationTableService organizationTableService;
    @Resource
    private ExtTlFilePaymentLogMapper extTlFilePaymentLogMapper;

    @Bean
    public Job repayFileLogPartitionJob() {
        return jobBuilderFactory.get("repayFileLogPartitionJob")
                .start(repayFileLogPartitionStep())
                .build();
    }

    @Bean
    public Step repayFileLogPartitionStep() {
        return stepBuilderFactory.get("repayFileLogPartitionStep")
                .tasklet(repayFileLogPartitionTasklet())
                .build();
    }

    @Bean
    @StepScope
    public Tasklet repayFileLogPartitionTasklet() {
        return (stepContribution, chunkContext) -> {
            // 获取当前业务日期
            PrOrganizationTable organization = organizationTableService.findByOrgIdForBatch(Constant.DEFAULT_ORG_NUMBER);
            Date businessDate = organization.getNextProcessingDate();
            // 判断是否存在当前业务日期60天以前的分区，如果存在则删除
            String date = new DateTime(businessDate).plusDays(-60).toString(DateUtils.DATE_PATTERN_ANOTHER);
            String partition = "p" + date;
            int res = extTlFilePaymentLogMapper.checkPartitionExists(partition);
            if (res > 0) {
                try {
                    extTlFilePaymentLogMapper.deletePartition(partition);
                } catch (Exception e) {
                    logger.error("删除分区失败,Partition:{}", partition);
                    throw new Exception("删除分区失败", e);
                }
            }
            // 判断是否存在当前业务日期31天以后的分区，如果不存在则建立
            date = new DateTime(businessDate).plusDays(31).toString(DateUtils.DATE_PATTERN_ANOTHER);
            partition = "p" + date;
            res = extTlFilePaymentLogMapper.checkPartitionExists(partition);
            if (res == 0) {
                try {
                    extTlFilePaymentLogMapper.createPartition(partition, date);
                } catch (Exception e) {
                    logger.error("新建分区失败,Partition:{}", partition);
                    throw new Exception("新建分区失败", e);
                }
            }
            return RepeatStatus.FINISHED;
        };
    }
}
